﻿#if NETCOREAPP3_0

namespace System.Text.Json.Serialization
{
    /// <summary>
    /// 转换 String 类型数据为 Number 数据
    /// </summary>
    public class StringToTimeSpanConverter : JsonConverter<TimeSpan>
    {
        /// <summary>
        /// 读取方法
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="typeToConvert"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                if (TimeSpan.TryParse(reader.GetString(), out var value)) return value;
            }
            return TimeSpan.Zero;
        }

        /// <summary>
        /// 写入方法
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="options"></param>
        public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString());
        }
    }
}
#endif
